import { asyncRouterMap, constantRouterMap } from '@/config/router.config'
import { postAction } from '@/api/manage'
/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = -1
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.indexOf(permission[i])
      if (flag >= 0) {
        return true
      }
    }
    return false
  }
  return true
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.indexOf(roles.id)
  } else {
    return true
  }
}

function filterAsyncRouter(routerMap, roles) {
  const accessedRouters = routerMap.filter((route) => {
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

function generaMenu(routes, data) {
  data.forEach((item) => {
    if (!item.component) {
      item.component = item.uri
    }
    const menu = makeMenu(item)
    if (item.redirect) {
      menu.redirect = item.redirect
    }
    if (item.children) {
      let childrenMenu = []
      item.children.forEach((c) => {
        if (c.type == 1) {
          childrenMenu.push(c)
        } else {
          routes.push(makeMenu(c))
        }
      })
      generaMenu(menu.children, childrenMenu)
    }
    routes.push(menu)
  })
}
function makeMenu(item) {
  let menu = {
    path: item.path,
    component: (resolve) => require([`@/${item.component}.vue`], resolve),
    children: [],
    name: item.name,
    id: item.id,
    parentId: item.parentId,
    type: item.type,
    hidden: item.hidden,
    meta: {},
  }
  if (item.meta) {
    menu.meta = {
      name: item.name,
      id: item.id,
      parentId: item.parentId,
      type: item.type,
      hidden: item.hidden,
      ...JSON.parse(item.meta),
    }
  } else {
    menu.meta = {
      name: item.name,
      id: item.id,
      parentId: item.parentId,
      type: item.type,
      hidden: item.hidden,
    }
  }
  return menu
}
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    hteSystemMenu: [],
  },
  mutations: {
    SET_ROUTERS: (state, data) => {
      state.addRouters = data
      state.routers = constantRouterMap.concat(data)
    },
    SET_PERSISTENCE_ROUTERS: (state, data) => {
      state.hteSystemMenu = data
    },
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise((resolve) => {
        const { roles } = data
        let accessedRouters
        accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
    // 动态添加主界面路由，需要缓存
    UpdateAppRouter({ commit }, routes) {
      return new Promise(async (resolve) => {
        let routelist = routes.constRoutes
        let asyncTrees = []//window.sessionStorage.getItem('asyncTrees')?JSON.parse(sessionStorage.getItem('asyncTrees')):[]
        if (!asyncTrees || asyncTrees.length <= 0) {
          let res = await postAction('/hteSystemMenu/tree', {})
          if (res.success) {
            window.sessionStorage.setItem('asyncTrees',JSON.stringify(res.result))
            asyncTrees = res.result
          }
        }
        let asyncRoutes = []
        if (asyncTrees && asyncTrees.length > 0) {
          generaMenu(asyncRoutes, asyncTrees)
          commit('SET_PERSISTENCE_ROUTERS', asyncRoutes)
        }
        routelist = [...routelist, ...asyncRoutes]
        commit('SET_ROUTERS', routelist)
        resolve()
      })
    },
  },
}

export default permission
